package com.hxht.cmp.exception;

import com.hxht.cmp.common.enums.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author alice on 2017/4/28 0028
 * @version 1.0
 * @since 1.0
 */
public class GlobalExceptionResolver extends SimpleMappingExceptionResolver {
    private final Logger log = LoggerFactory.getLogger(GlobalExceptionResolver.class);

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//        log.error("request url:" +request.getRequestURI());
//        log.error("system error now ,error message:" + ex.getMessage());
//        String viewName = determineViewName(ex, request);
//        response.setCharacterEncoding("UTF-8");
//        response.setStatus(HttpServletResponse.SC_OK);
//        if (!StringUtils.isEmpty(viewName)) {// HTML格式返回
//            log.error("error 信息将会以页面形式进行返回");
//            if (!(request.getHeader("accept").contains("application/json") || (request.getHeader("X-Requested-With") != null && request
//                    .getHeader("X-Requested-With").contains("XMLHttpRequest")))) {
//                // 如果不是异步请求
//                // Apply HTTP status code for error views, if specified.
//                // Only apply it if we're processing a top-level request.
//                Integer statusCode = determineStatusCode(request, viewName);
//                if (!StringUtils.isEmpty(statusCode)) {
//                    applyStatusCodeIfPossible(request, response, statusCode);
//                }
//                if (request.getRequestURI().contains("index")) {
//                    viewName = "login";
//                }
//                return getModelAndView(viewName, ex, request);
//            } else {// JSON格式返回
//                log.error("error 信息将会以页面形式进行返回");
//                try {
//                    PrintWriter writer = response.getWriter();
//                    writer.write(ResultCode.SERVER_ERROR.getMessage());
//                    writer.flush();
//                } catch (IOException e) {
//                    log.error(e.getMessage());
//                }
//                return null;
//            }
//        } else {
//            return null;
//        }
        return null;
    }
}
